Here is the terraform code I have used to create a service account and bind a role to it:
resource "google_service_account" "sa-name" {
account_id = "sa-name"
display_name = "SA"
}
resource "google_project_iam_binding" "firestore_owner_binding" {
role = "roles/datastore.owner"
members = [
"serviceAccount:sa-name#${var.project}.iam.gserviceaccount.com",
]
depends_on = [google_service_account.sa-name]
}
Above code worked great... except it removed the datastore.owner from any other service account in the project that this role was previously assigned to. We have a single project that many teams use and there are service accounts managed by different teams. My terraform code would only have our team's service accounts and we could end up breaking other teams service accounts.
Is there another way to do this in terraform?
This of course can be done via GCP UI or gcloud cli without any issue or affecting other SAs.
From terraform docs, "google_project_iam_binding" is Authoritative. Sets the IAM policy for the project and replaces any existing policy already attached. That means that it replaces completely members for a given role inside it.
To just add a role to a new service account, without editing everybody else from that role, you should use the resource "google_project_iam_member":
resource "google_service_account" "sa-name" {
account_id = "sa-name"
display_name = "SA"
}
resource "google_project_iam_member" "firestore_owner_binding" {
project = <your_gcp_project_id_here>
role = "roles/datastore.owner"
member = "serviceAccount:${google_service_account.sa-name.email}"
}
Extra change from your sample: the use of service account resource email generated attribute to remove the explicit depends_on. You don't need the depends_on if you do it like this and you avoid errors with bad configuration.
Terraform can infer the dependency from the use of a variable from another resource. Check the docs here to understand this behavior better.
It's an usual problem with Terraform. Either you do all with it, or nothing. If you are between, unexpected things can happen!!
If you want to use terraform, you have to import the existing into the tfstate. Here the doc for the bindind, and, of course, you have to add all the account in the Terraform file. If not, the binding will be removed, but this time, you will see the deletion in the tf plan.
Related
I have two Cloud Run services. Service U has Unauthenticated access open to all users. Service R I want the access Restricted so that only Service A can invoke it.
This gist has a pretty succinct implementation using the CLI. My services are configured with Terraform and I'm trying to translate, but also understand:
Based on this I thought I could allow Service R access by Service U by adding U's service account (I added service_account: service-u-sa#abcdefg.iam.gserviceaccount.com to Service U's google_cloud_run_service.spec.service_account_name) in the same way I open up access to all users. Here is allUsers:
resource "google_cloud_run_service" "service_r" {
name = local.service_name
# ... rest of the service definition
}
resource "google_cloud_run_service_iam_member" "run_all_users" {
service = google_cloud_run_service.service_r.name
location = google_cloud_run_service.service_r.location
role = "roles/run.invoker"
member = "allUsers"
depends_on = [
google_cloud_run_service.service_r,
]
}
And I amended it to be for just one service account with:
resource "google_cloud_run_service_iam_member" "run_all_users" {
service = google_cloud_run_service.service_r.name
location = google_cloud_run_service.service_r.location
role = "roles/run.invoker"
member = "serviceAccount:service-u-sa#abcdefg.iam.gserviceaccount.com
depends_on = [
google_cloud_run_service.service_b,
]
}
This does not seem to work.
However, adding a data source that creates a policy does seem to work:
data "google_iam_policy" "access_policy" {
binding {
role = "roles/run.invoker"
members = [
"serviceAccount:service-u-sa#abcdefg.iam.gserviceaccount.com",
]
}
}
resource "google_cloud_run_service_iam_policy" "cloud_run_policy" {
location = google_cloud_run_service.service_r.location
project = google_cloud_run_service.service_r.project
service = google_cloud_run_service.service_r.name
policy_data = data.google_iam_policy.access_policy.policy_data
}
I've read on this SO answer (and elsewhere) that service accounts are identities as well as resources. Is that what is happening here? That is, rather than using the service account service-b-sa#abcdefg.iam.gserviceaccount.com as an identity, I am attaching it to Service R as a "resource"? Is that what a "policy" is in this context? And is there anywhere in the GCR UI where I can see these relationships?
Ok, I will try to clarify the wording and the situation, even if I didn't catch what changed between your 2 latest piece of code.
Duality
Yes, Service Account have duality: they are identity AND resources. And because they are a resource, you can grant on identity on it (especially to perform impersonation).
Access Policy
It's simply a binding between an identity and a role. Then you have to apply that binding to a resource to grant the identity the role on the resource. This trio is an IAM authorization policy, or policy in short.
Service and Service Account
Your question is hard to understand because you mix the Cloud Run service, and the service account.
A Cloud Run service has an identity: the runtime service account.
A Cloud Run service CAN'T have access to another Cloud Run service. But the identity of a Cloud Run service can access another Cloud Run service.
That being said, there is no difference between your 2 latest piece of code. In fact yes, there is a difference but the second definition is much more restrictive than the first one.
In the latest one, you use ....._iam_policy. It means you REPLACE all the policies. In other word, the "access_policy" override all the existing permissions.
In the case before, you use ....._iam_member. It means you simply add a policy to the current resource, without changing the existing ones.
That's why, the result is the same: service-u has the role Invoker on the service_r.
Can you try again? the issue is somewhere else.
In Terraform I enable services like so:
resource "google_project_service" "apigateway" {
service = "apigateway.googleapis.com"
}
Afterwards I ensure that I am referencing the service account of apigateway (service-123#gcp-sa-apigateway.iam.gserviceaccount.com) only after the resource was created.
Now it does happen sometimes that when using the email of sa, I get an error that the service account is not present:
Error 400: Service account service-123#gcp-sa-apigateway.iam.gserviceaccount.com does not exist.
I double checked in API Explorer that the API is enabled!
This in turn does happen for apigateway the same way as for others (e.g. cloudfunctions).
So I am wondering how do I ensure that the service account is created?
Naively I assumed creating google_project_services should do the trick but that seems not be true in every case. Documentation around Google service account is pretty sparse it seems :(
As John Hanley remarks, you can create this dependency in terraform with depends_on.
As you can see on the following comment, the service account will be created but the key will be assigned until the first sentence is done.
resource "google_service_account" "service_account" {
account_id = "terraform-test"
display_name = "Service Account"
}
resource "google_service_account_key" "mykey" {
service_account_id = google_service_account.service_account.id
public_key_type = "TYPE_X509_PEM_FILE"
depends_on = [google_service_account.service_account]
}
Also, if the service account is already created on the GCP platform only is executed the key statement.
It is important noticed that the account that you are using for this configuration needs to have the required IAM permission to create an account.
Found out about google_project_service_identity.
So since I saw this problem with cloudfunctions you could create a google_project_service_identity.cloudfunctions and hope for a detailed error message.
Sadly this is not available for all, e.g. apigateway.
For apigateway specifically, Google Support confirmed that undocumented behavior is the SA gets created lazily when creating first resource.
My objective is to be able to set up an IAM Role which can assume a role of a certain IAM user. After the creation of the role, I would like to come back later and modify this role by adding external IDs to establish a trust relationship. Let me illustrate with an example:
Let's say I want to create role:
resource "aws_iam_role" "happy_role" {
name = "happy-role"
assume_role_policy = data.aws_iam_policy_document.happy_assume_rule_policy.json
}
Let's also assume that happy_assume_role_policy looks something like:
data "aws_iam_policy_document" "happy_assume_role_policy" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "AWS"
identifiers = [var.some_iam_user_arn]
}
}
}
Now, I will use the created role to create an external integration. But once I am done creating that integration, I want to go back to the role I originally created and modify it's assumed role policy. So now I want to add a condition to the assume role policy and make it look like:
data "aws_iam_policy_document" "happy_assume_role_policy" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
principals {
type = "AWS"
identifiers = [var.snowflake_iam_user_arn]
}
condition {
test = "StringEquals"
values = [some_integration.integration.external_id]
variable = "sts:ExternalId"
}
}
}
In other words, my workflow should be like:
Create role without assume conditions
Create an integration with that role
Take the ID from the created integration and go back to the created role and add a condition on it
Edit:
By "integration" I mean something like this. Once an Integration is created, there is an outputted ID, and then I need to take that ID and feed it back to the Assume Role I originally created. That should happen everytime I add a new integration.
I first tried to create two IAM roles, one for managing the integration creation, and another for managing the integration itself. That ran without circular reference errors; however, I was not able to establish a connection from the storage to the database, as it needs to be the same IAM Role creating and managing the integration.
This is what I have ended up doing (still not good for an accepted way to do it IMO). I created a role (with targeting) like:
resource "aws_iam_role" "happy_role" {
name = "happy-role"
assume_role_policy = data.aws_iam_policy_document.basic_policy.json
}
And used a basic assume role policy (without conditions). And then for the next run, I applied (without targeting) and it worked.
I followed the approach mentioned here, How to create a Snowflake Storage Integration with AWS S3 with Terraform?
As part of Storage Integration creation, just provide the role arn which is manually constructed without the resource is created. Terraform wont complain. Then create the role with the assume policy referring to the External Id and User ARN created by the Storage Integration
I am trying to assign a IAM policy document to an existing Cloud Build Service Account, but its failing for some reason.
following is my iam policy
data "google_iam_policy" "vulznotepolicy" {
binding {
role = "roles/containeranalysis.notes.occurrences.viewer"
members = [
"serviceaccount:<project_number>#cloudbuild.gserviceaccount.com"
]
}
}
following is policy assignment to Service account
resource "google_service_account_iam_policy" "buildsa" {
service_account_id = "serviceaccount:<project_number>#cloudbuild.gserviceaccount.com"
policy_data = data.google_iam_policy.vulznotepolicy.policy_data
}
service account id doesn't accept the format that i have provided. I have given just the <project_number> still it doesn't accept. Not sure what the issue is
As suggested rightly by John, i added the roles to the service account using the following
resource "google_project_iam_policy" "buildsa" {
project = var.project_id
policy_data = data.google_iam_policy.vulznotepolicy.policy_data
}
Although this works but can cause serious problems as follows. Please proceed with caution
Since this is an authoritative operation, it will lock you out of your account if the operations are not carefully managed. This is from terraform "It's not recommended to use google_project_iam_policy with your provider project to avoid locking yourself out, and it should generally only be used with projects fully managed by Terraform. If you do use this resource, it is recommended to import the policy before applying the change."
I can see that you’re trying to give the Cloud Build Service account some IAM permissions using Terraform.
I would start by reading this document about IAM Roles on Cloud Build [1], then you can check how the Cloud Build Service Account behaves [2], and then how to configure it [3].
Since you’re using Terraform, I would also have a look here [4].
These can help you understand why you’re running into this issue, as pointed out in a comment.
[1] https://cloud.google.com/cloud-build/docs/iam-roles-permissions
[2] https://cloud.google.com/cloud-build/docs/cloud-build-service-account
[3] https://cloud.google.com/cloud-build/docs/securing-builds/configure-access-for-cloud-build-service-account#before_you_begin
[4] https://www.terraform.io/docs/providers/google/r/google_service_account_iam.html
I want to attach one of the pre-existing AWS managed roles to a policy, here's my current code:
resource "aws_iam_role_policy_attachment" "sto-readonly-role-policy-attach" {
role = "${aws_iam_role.sto-test-role.name}"
policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}
Is there a better way to model the managed policy and then reference it instead of hardcoding the ARN? It just seems like whenever I hardcode ARNs / paths or other stuff like this, I usually find out later there was a better way.
Is there something already existing in Terraform that models managed policies? Or is hardcoding the ARN the "right" way to do it?
The IAM Policy data source is great for this. A data resource is used to describe data or resources that are not actively managed by Terraform, but are referenced by Terraform.
For your example, you would create a data resource for the managed policy as follows:
data "aws_iam_policy" "ReadOnlyAccess" {
arn = "arn:aws:iam::aws:policy/ReadOnlyAccess"
}
The name of the data source, ReadOnlyAccess in this case, is entirely up to you. For managed policies I use the same name as the policy name for the sake of consistency, but you could just as easily name it readonly if that suits you.
You would then attach the IAM policy to your role as follows:
resource "aws_iam_role_policy_attachment" "sto-readonly-role-policy-attach" {
role = "${aws_iam_role.sto-test-role.name}"
policy_arn = "${data.aws_iam_policy.ReadOnlyAccess.arn}"
}
When using values that Terraform itself doesn't directly manage, you have a few options.
The first, simplest option is to just hard-code the value as you did here. This is a straightforward answer if you expect that the value will never change. Given that these "canned policies" are documented, built-in AWS features they likely fit this criteria.
The second option is to create a Terraform module and hard-code the value into that, and then reference this module from several other modules. This allows you to manage the value centrally and use it many times. A module that contains only outputs is a common pattern for this sort of thing, although you could also choose to make a module that contains an aws_iam_role_policy_attachment resource with the role set from a variable.
The third option is to place the value in some location that Terraform can retrieve values from, such as Consul, and then retrieve it from there using a data source. With only Terraform in play, this ends up being largely equivalent to the second option, though it means Terraform will re-read it on each refresh rather than only when you update the module using terraform init -upgrade, and thus this could be a better option for values that change often.
The fourth option is to use a specialized data source that can read the value directly from the source of truth. Terraform does not currently have a data source for fetching information on AWS managed policies, so this is not an option for your current situation, but can be used to fetch other AWS-defined data such as the AWS IP address ranges, service ARNs, etc.
Which of these is appropriate for a given situation will depend on how commonly the value changes, who manages changes to it, and on the availability of specialized Terraform data sources.
I got a similar situation, and I don't want to use the arn in my terraform script for two reasons,
If we do it on the Web console, we don't really look at the arn, we search the role name, then attach it to the role
The arn is not easy to remember, looks like is not for human
I would rather use the policy name, but not the arn, here is my example
# Get the policy by name
data "aws_iam_policy" "required-policy" {
name = "AmazonS3FullAccess"
}
# Create the role
resource "aws_iam_role" "system-role" {
name = "data-stream-system-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "ec2.amazonaws.com"
}
},
]
})
}
# Attach the policy to the role
resource "aws_iam_role_policy_attachment" "attach-s3" {
role = aws_iam_role.system-role.name
policy_arn = data.aws_iam_policy.required-policy.arn
}