JohnHillegass: Thanks for the add! Something to be aware of there is that it will look for the countUnit if countType is sinceImagePushed. 
https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html
But fortunately there is already a validation in place on line 203. 
myoung34: Right, and that'll error at the PUT request from cloud-custodian which is fine IMO
kapilt: removing validation isn't the same as applying the conditional validation, we want up front validation.
myoung34: @kapilt that validation does exist [here](https://github.com/cloud-custodian/cloud-custodian/blob/master/c7n/resources/ecr.py#L203)
kapilt: > @kapilt that validation does exist [here](https://github.com/cloud-custodian/cloud-custodian/blob/master/c7n/resources/ecr.py#L204)

cool, thanks.. I was going down the rabbit hole of doing this in jsonschema

```diff
+            'anyOf': [
+                {"properties": {
+                    "countType": { "const": "sinceImagePushed" },
+                    "required": ["countUnit"]}},
+                {"properties": {
+                    "countType": { "const": "imageCountMoreThan" },
+                    "required": ["countNumber"]}},
+            ],
```

myoung34: I updated my comment, its called at validation time already so it shouldnt be necessary to add complex schema validation
kapilt: > I updated my comment, its called at validation time already so it shouldnt be necessary to add complex schema validation

the issue is that python validation isn't fully correct to handle all cases (per the note I wrote inline to that function), ie. this is missing countNumber and passes validation, but blows up at runtime.


```
policies: 
  - name: ecr-no-lifecycle
    resource: aws.ecr
    actions:
      - type: set-lifecycle
        rules:
          - rulePriority: 1
            description: "Cleans up older untagged images"
            selection:
              tagStatus: untagged
              countType: imageCountMoreThan
            action:
              type: expire
```


the additional jsonschema lines in my previous comment tried to cover this, or we can add more python code and a unit test to the validate method.


kapilt: going through https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html#lp_tag_status

it looks like tagStatus, countType, and countNumber should be required unconditionally in the schema.

kapilt: i went ahead and added a commit and test to cover off on fixing validation (three required attributes on each rule in jsonschema), and the case of countUnit specified on imageCountMoreThan in the rule validate function.
diff --git a/c7n/resources/ecr.py b/c7n/resources/ecr.py
index b2c8d8ae7..057232940 100644
--- a/c7n/resources/ecr.py
+++ b/c7n/resources/ecr.py
@@ -174,7 +174,7 @@ LIFECYCLE_RULE_SCHEMA = {
         'selection': {
             'type': 'object',
             'addtionalProperties': False,
-            'required': ['countType', 'countUnit'],
+            'required': ['countType', 'countNumber', 'tagStatus'],
             'properties': {
                 'tagStatus': {'enum': ['tagged', 'untagged', 'any']},
                 'tagPrefixList': {'type': 'array', 'items': {'type': 'string'}},
@@ -197,7 +197,7 @@ def lifecycle_rule_validate(policy, rule):
     if (rule['selection']['tagStatus'] == 'tagged' and
             'tagPrefixList' not in rule['selection']):
         raise PolicyValidationError(
-            ("{} has invalid lifecycle rule {} tagprefixlist "
+            ("{} has invalid lifecycle rule {} tagPrefixList "
              "required for tagStatus: tagged").format(
                  policy.name, rule))
     if (rule['selection']['countType'] == 'sinceImagePushed' and
@@ -206,6 +206,12 @@ def lifecycle_rule_validate(policy, rule):
             ("{} has invalid lifecycle rule {} countUnit "
              "required for countType: sinceImagePushed").format(
                  policy.name, rule))
+    if (rule['selection']['countType'] == 'imageCountMoreThan' and
+            'countUnit' in rule['selection']):
+        raise PolicyValidationError(
+            ("{} has invalid lifecycle rule {} countUnit "
+             "invalid for countType: imageCountMoreThan").format(
+                 policy.name, rule))
 
 
 @ECR.filter_registry.register('lifecycle-rule')
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 1ac6d0612..569548c6b 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -24,5 +24,5 @@
 # we don't export dev requirements of subpackages (due to editable/distribution above)
 # so explicitly list them here.
 vcrpy-unittest==0.1.7
-parameterized==0.7.1
-fakeredis==1.2.1
+parameterized==0.7.4
+fakeredis==1.4.0

aws: ecr.actions.set-lifecycle's countUnit says it is required for countType imageCountMoreThan
**Describe the bug**
ecr.actions.set-lifecycle's countUnit says it is required for countType imageCountMoreThan when it should only used when the countType is set to sinceImagePushed.

> The tagPrefixList parameter is only used if tagStatus is tagged. The countUnit parameter is only used if countType is sinceImagePushed. The countNumber parameter is only used if countType is set to imageCountMoreThan. 

Ref: https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html

**To Reproduce**
Steps to reproduce the behavior:

1. Create policy
2. Run policy

**Expected behavior**
Policy should work without having to set countUnit

**Background (please complete the following information):**
 - OS: OSX 10.15
 - Custodian Version: custodian-cask
 - Policy:
```yaml
policies: 
  - name: ecr-no-lifecycle
    resource: aws.ecr
    filters:
      - type: lifecycle-rule
        state: false
    actions:
      - type: set-lifecycle
        rules:
          - rulePriority: 1
            description: "Cleans up older untagged images"
            selection:
              tagStatus: untagged
              countType: imageCountMoreThan
              # c7n requirement. value is ignored because the type is NOT sinceImagePushed
              # countUnit: days
              countNumber: 5
            action:
              type: expire
```
 - Traceback: [if applicable, please exclude sensitive/account information]
```
✗ custodian-cask run -c test-policies/ecr-no-lifecycle.yml --dryrun -s out --verbose --cache-period 0

Custodian Cask 20190904.1 (cloudcustodian/c7n:latest)
Skipped image pull - Last checked 16 minutes ago.

2020-04-14 17:11:07,137: custodian.commands:ERROR invalid policy file: /home/custodian/ecr-no-lifecycle.yml error: Failed to validate policy ecr-no-lifecycle
 Error on policy:ecr-no-lifecycle resource:ecr
'countUnit' is a required property

Failed validating 'required' in schema[12]['properties']['rules']['items']['properties']['selection']:
    {'addtionalProperties': False,
     'properties': {'countNumber': {'type': 'integer'},
                    'countType': {'enum': ['imageCountMoreThan',
                                           'sinceImagePushed']},
                    'countUnit': {'enum': ['hours', 'days']},
                    'tagPrefixList': {'items': {'type': 'string'},
                                      'type': 'array'},
                    'tagStatus': {'enum': ['tagged', 'untagged', 'any']}},
     'required': ['countType', 'countUnit'],
     'type': 'object'}

On instance['rules'][0]['selection']:
    {'countNumber': 5,
     'countType': 'imageCountMoreThan',
     'tagStatus': 'untagged'}
2020-04-14 17:11:07,137: custodian.commands:ERROR Found 1 errors.  Exiting.
```
 - `custodian version --debug` output

**Additional context**
Add any other context about the problem here.

diff --git a/tests/test_ecr.py b/tests/test_ecr.py
index a450e3380..7c535cbf8 100644
--- a/tests/test_ecr.py
+++ b/tests/test_ecr.py
@@ -13,12 +13,29 @@
 # limitations under the License.
 import json
 
-from .common import BaseTest, functional
+from .common import BaseTest, functional, Bag
 from botocore.exceptions import ClientError
 
+from c7n.exceptions import PolicyValidationError
+from c7n.resources.ecr import lifecycle_rule_validate
+
 
 class TestECR(BaseTest):
 
+    def test_rule_validation(self):
+        policy = Bag(name='xyz')
+        with self.assertRaises(PolicyValidationError) as ecm:
+            lifecycle_rule_validate(
+                policy, {'selection': {'tagStatus': 'tagged'}})
+        self.assertIn('tagPrefixList required', str(ecm.exception))
+        with self.assertRaises(PolicyValidationError) as ecm:
+            lifecycle_rule_validate(
+                policy, {'selection': {
+                    'tagStatus': 'untagged',
+                    'countNumber': 10, 'countUnit': 'days',
+                    'countType': 'imageCountMoreThan'}})
+        self.assertIn('countUnit invalid', str(ecm.exception))
+
     def create_repository(self, client, name):
         """ Create the named repository. Delete existing one first if applicable. """
         existing_repos = {

pip install -e .[dev]
parse_log_pytest
requirements.txt
pytest pytest-cov pytest-xdist pytest-mock pytest-asyncio
apt-get update apt-get install -y gcc
3.9
requirements.txt
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
apipkg==1.5
appdirs==1.4.3
argcomplete==1.11.1
attrs==19.3.0
aws-xray-sdk==2.4.3
bleach==3.1.4
boto3==1.12.36
botocore==1.15.36
-e git+https://github.com/cloud-custodian/cloud-custodian.git@577aefaf34557a445470be106c954e5d667dc36e#egg=c7n
certifi==2020.4.5.1
cffi==1.14.0
chardet==3.0.4
coverage==5.0.4
cryptography==2.9
distlib==0.3.0
docutils==0.15.2
entrypoints==0.3
exceptiongroup==1.2.2
execnet==1.7.1
filelock==3.0.12
flake8==3.7.9
future==0.18.2
idna==2.9
importlib-metadata==1.6.0
iniconfig==2.1.0
jeepney==0.4.3
jmespath==0.9.5
jsonpatch==1.25
jsonpickle==1.3
jsonpointer==2.0
jsonschema==3.2.0
keyring==21.2.0
mccabe==0.6.1
mock==4.0.2
more-itertools==8.2.0
multidict==4.7.5
packaging==20.3
pkginfo==1.5.0.1
placebo==0.9.0
pluggy==1.5.0
psutil==5.7.0
py==1.8.1
pycodestyle==2.5.0
pycparser==2.20
pyflakes==2.1.1
Pygments==2.6.1
pyparsing==2.4.7
pyrsistent==0.16.0
pytest==8.3.5
pytest-asyncio==0.26.0
pytest-cov==2.8.1
pytest-forked==1.1.3
pytest-mock==3.14.0
pytest-xdist==1.31.0
python-dateutil==2.8.1
PyYAML==5.3.1
readme-renderer==25.0
requests==2.23.0
requests-toolbelt==0.9.1
s3transfer==0.3.3
SecretStorage==3.1.2
six==1.14.0
tabulate==0.8.7
toml==0.10.0
tomli==2.2.1
tox==3.14.6
tqdm==4.45.0
twine==3.1.1
typing_extensions==4.13.0
urllib3==1.25.8
vcrpy==4.0.2
virtualenv==20.0.16
wcwidth==0.1.9
webencodings==0.5.1
wrapt==1.12.1
yarl==1.4.2
zipp==3.1.0

name: cloud-custodian
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - ca-certificates=2025.2.25=h06a4308_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=3.0.16=h5eee18b_0
  - pip=25.0=py39h06a4308_0
  - python=3.9.21=he870216_1
  - readline=8.2=h5eee18b_0
  - setuptools=75.8.0=py39h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tzdata=2025a=h04d1e81_0
  - wheel=0.45.1=py39h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - apipkg==1.5
      - appdirs==1.4.3
      - argcomplete==1.11.1
      - attrs==19.3.0
      - aws-xray-sdk==2.4.3
      - bleach==3.1.4
      - boto3==1.12.36
      - botocore==1.15.36
      - c7n==0.9.0
      - certifi==2020.4.5.1
      - cffi==1.14.0
      - chardet==3.0.4
      - coverage==5.0.4
      - cryptography==2.9
      - distlib==0.3.0
      - docutils==0.15.2
      - entrypoints==0.3
      - exceptiongroup==1.2.2
      - execnet==1.7.1
      - filelock==3.0.12
      - flake8==3.7.9
      - future==0.18.2
      - idna==2.9
      - importlib-metadata==1.6.0
      - iniconfig==2.1.0
      - jeepney==0.4.3
      - jmespath==0.9.5
      - jsonpatch==1.25
      - jsonpickle==1.3
      - jsonpointer==2.0
      - jsonschema==3.2.0
      - keyring==21.2.0
      - mccabe==0.6.1
      - mock==4.0.2
      - more-itertools==8.2.0
      - multidict==4.7.5
      - packaging==20.3
      - pkginfo==1.5.0.1
      - placebo==0.9.0
      - pluggy==1.5.0
      - psutil==5.7.0
      - py==1.8.1
      - pycodestyle==2.5.0
      - pycparser==2.20
      - pyflakes==2.1.1
      - pygments==2.6.1
      - pyparsing==2.4.7
      - pyrsistent==0.16.0
      - pytest==8.3.5
      - pytest-asyncio==0.26.0
      - pytest-cov==2.8.1
      - pytest-forked==1.1.3
      - pytest-mock==3.14.0
      - pytest-xdist==1.31.0
      - python-dateutil==2.8.1
      - pyyaml==5.3.1
      - readme-renderer==25.0
      - requests==2.23.0
      - requests-toolbelt==0.9.1
      - s3transfer==0.3.3
      - secretstorage==3.1.2
      - six==1.14.0
      - tabulate==0.8.7
      - toml==0.10.0
      - tomli==2.2.1
      - tox==3.14.6
      - tqdm==4.45.0
      - twine==3.1.1
      - typing-extensions==4.13.0
      - urllib3==1.25.8
      - vcrpy==4.0.2
      - virtualenv==20.0.16
      - wcwidth==0.1.9
      - webencodings==0.5.1
      - wrapt==1.12.1
      - yarl==1.4.2
      - zipp==3.1.0
prefix: /opt/conda/envs/cloud-custodian

tests/test_ecr.py::TestECR::test_rule_validation
tests/test_ecr.py::TestECR::test_ecr_lifecycle_delete tests/test_ecr.py::TestECR::test_ecr_lifecycle_policy tests/test_ecr.py::TestECR::test_ecr_no_policy tests/test_ecr.py::TestECR::test_ecr_remove_matched tests/test_ecr.py::TestECR::test_ecr_remove_named tests/test_ecr.py::TestECR::test_ecr_set_immutability tests/test_ecr.py::TestECR::test_ecr_set_lifecycle tests/test_ecr.py::TestECR::test_ecr_set_scanning tests/test_ecr.py::TestECR::test_ecr_tags
requirements-dev.txt c7n/resources/ecr.py
requirements-dev.txt c7n/resources/ecr.py